<!-- 后端账户信息 -->
<template>
  <div class="table">
    <div class="container">
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-icon>
              <Search />
            </el-icon> 查询条件：
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row :gutter="10">
        <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.user_name" placeholder="用户名"></el-input>
        </el-col>
        <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.mobile" placeholder="手机号"></el-input>
        </el-col>
        <el-col :xl="6" :lg="6" :md="12" :sm="24" style="margin-bottom:10px">
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>查询结果：</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="handle-box">
        <el-button type="primary" :icon="Plus" class="mr10" :disabled="disabledbtn" @click="editVisible = true">新增
        </el-button>
        <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete('deleteUserInfo')">
          <template #reference>
            <el-button type="danger" :icon="Delete" class="mr10" :disabled="disabledbtn">批量删除
            </el-button>
          </template>
        </el-popconfirm>
      </div>
      <el-table :data="tableState.tableList" border class="table" ref="multipleTableRef" v-loading="tableLoading"
        :reserve-selection="true" @row-dblclick="rowDblclick">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="role_name" label="角色" align="center">
        </el-table-column>
        <el-table-column prop="agency_name" label="组织" align="center">
        </el-table-column>
        <el-table-column prop="user_name" label="用户名" align="center">
        </el-table-column>
        <el-table-column prop="nick_name" label="昵称" align="center">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" align="center">
        </el-table-column>
        <el-table-column prop="status_name" label="状态" align="center">
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" text :icon="View" @click="handleViewEdit(scope.row, 'view', '查看')">
              查看
            </el-button>
            <el-button type="primary" size="small" text :icon="Edit" @click="handleViewEdit(scope.row, 'edit', '编辑')">
              编辑
            </el-button>
            <div class="display-inline-block">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo('deleteUserInfo', [id])">
                <template #reference>
                  <el-button text :icon="Delete" size="small" class="red" @click="id = scope.row.id">删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
            <div class="display-inline-block">
              <el-popconfirm placement="top" width="160" title="你确定要重置密码吗?"
                @confirm="resetPassword('updataResetUserPasswordInfo', { id: id })">
                <template #reference>
                  <el-button type="primary" text :icon="RefreshRight" size="small" @click="id = scope.row.id">
                    重置密码</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div class="display-inline-block" v-if="scope.row.status === '1'">
              <el-popconfirm placement="top" width="160" title="你确定要禁用账号吗?"
                @confirm="changeAccountStatus('updataAccountStatusInfo', { id: id, status: 0 })">
                <template #reference>
                  <el-button text :icon="CircleClose" class="warning" size="small" @click="id = scope.row.id">禁用账号
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
            <div class="display-inline-block" v-if="scope.row.status === '0'">
              <el-popconfirm placement="top" width="160" title="你确定要启用账号吗?"
                @confirm="changeAccountStatus('updataAccountStatusInfo', { id: id, status: 1 })">
                <template #reference>
                  <el-button text :icon="CircleCheck" class="cyan" @click="id = scope.row.id">启用账号
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background @update:current-page="handleCurrentChange" @update:page-size="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper" :page-size="searchCondition.size"
          :current-page="searchCondition.current" :page-sizes="pageSizes" :total="total" :hide-on-single-page="false">
        </el-pagination>
      </div>
    </div>

    <!-- 新增编辑查看弹出框 -->
    <el-dialog :title="dialogTitle" v-model="editVisible" width="60%" :close-on-click-modal="closeOnClickModal"
      draggable @closed="closedFormDialog">
      <el-form ref="userFormRef" :model="userForm" :rules="rules" v-loading="formLoading" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="用户名：" prop="user_name">
              <el-input v-model.trim="userForm.user_name" :disabled="usernameDisabled" placeholder="请填写用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="昵称：" prop="nick_name">
              <el-input v-model.trim="userForm.nick_name" placeholder="请填写昵称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="角色：" prop="role_id">
              <el-select v-model.trim="userForm.role_id" placeholder="请选择角色" class="">
                <el-option v-for="item in state.selectRole" :label="item.name" :value="item.id" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="组织：" prop="agency_id">
              <el-select v-model.trim="userForm.agency_id" placeholder="请选择组织" class="">
                <el-option v-for="item in state.selectOrganization" :label="item.name" :value="item.id" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="手机号：" prop="mobile">
              <el-input v-model.trim="userForm.mobile" placeholder="手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="11">
            <el-form-item label="头像：" prop="avatar">
              <div class="w-spec">
                <el-upload class="avatar-uploader" v-if="!userForm.avatar" :action="uploadUrl" :data="uploadData"
                  :show-file-list="false"
                  :on-success="(response) => handleResourcesUploadSuccess(response, userForm, 'avatar')"
                  :before-upload="(file) => handleBeforeUpload(file)">
                  <el-icon class="el-icon-plus avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
                <div class="wzg-continer-img" v-else>
                  <img :src="userForm.avatar === '' ? '' : imageUrl + userForm.avatar" alt="头像" class="wzg-img">
                  <el-icon class="el-icon-close" @click="handleDeleteResources(userForm, 'avatar')">
                    <Close />
                  </el-icon>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn"
            @click="submitForm('commonUserInfoListInfo', getTableInfo)">确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { View, Delete, Edit, Search, Plus, Refresh, RefreshRight, CircleCheck, CircleClose } from '@element-plus/icons-vue';
import { api as Request, uploadUrl, imageUrl } from '@/utils/api';
import useResourceToken from '@/hooks/useResourceToken.js';

import { useTable } from '@/hooks/useTable.js';
import { useDialogForm } from '@/hooks/useDialogForm.js';
import useRules from '@/hooks/useRules.js';
import { useUpload } from '@/hooks/useUpload.js';

const rules = useRules('userRules');/* 校验规则 */
const disabledbtn = ref(false);/* 按钮可用与不可用 */
const formLoading = ref(false);/* 表单loading状态 */
let { total, pageSizes, multipleTableRef, tableLoading, tableState, searchCondition,
  handleCurrentChange, handleSizeChange, getTableInfo, searchInfo, resetSearch, batchDelete, deleteInfo, rowDblclick } =
  useTable({
    user_name: '',
    mobile: '',
    current: 1,
    size: 10
  }, 'getUserListInfo', disabledbtn);

let { formRef: userFormRef, formData: userForm, methodType, isDisabledbtn,
  closeOnClickModal, dialogTitle, editVisible, closedFormDialog,
  submitForm } = useDialogForm({
    id: '',
    user_name: '',
    nick_name: '',
    mobile: '',
    role_id: '',
    agency_id: '',
    avatar: ''
  }, disabledbtn, handleCustomOperation, formLoading);

let { uploadData,
  handleDeleteResources, handleResourcesUploadSuccess, handleBeforeUpload } = useUpload(disabledbtn, formLoading);

const state = reactive({
  selectOrganization: [],/* 组织 */
  selectRole: []
});

const usernameDisabled = ref(false);/* 用户名是否可编辑 */

const id = ref(-1);/* 删除时所需的编号 删除时的id */

/* 请求：获取组织数据 */
const getOrganizationInfo = () => {
  Request.getOrganizationInfo({})
    .then((res) => {
      state.selectOrganization = res.result;
    })
    .catch((res) => { });
}
/* 请求：获取角色数据 */
const getRoleInfo = () => {
  Request.getRoleInfo({})
    .then((res) => {
      state.selectRole = res.result;
    })
    .catch((res) => { });
}

/* 点击编辑按钮 */
const handleViewEdit = (row, code, name) => {
  if ('view' === code) {
    dialogTitle.value = name;
    isDisabledbtn.value = true;
    closeOnClickModal.value = true;
  } else if ('edit' === code) {
    dialogTitle.value = name;
    methodType.value = 'PUT';
  }
  usernameDisabled.value = true;
  /* nextTick 解决重置该表单项 初始化的数据问题 */
  nextTick(() => {
    userForm.id = row.id;
    userForm.user_name = row.user_name;
    userForm.nick_name = row.nick_name;
    userForm.role_id = row.role_id;
    userForm.agency_id = row.agency_id;
    userForm.mobile = row.mobile;
    userForm.avatar = row.avatar;
  });
  editVisible.value = true;
}

/*关闭模态框以后的自定义操作 */
function handleCustomOperation () {
  userForm.id = '';/* 这个还需要手动清除 */
  usernameDisabled.value = false;
  console.log(userForm);
}

/* 重置密码 */
const resetPassword = (method, data) => {
  /* 防止多次提交 */
  disabledbtn.value = true;
  formLoading.value = true;
  Request[method](data)
    .then((res) => {
      disabledbtn.value = false;
      formLoading.value = false;
      ElMessage.success(res.msg);
    })
    .catch((res) => {
      disabledbtn.value = false;
      formLoading.value = false;
    });
}

/* 启用禁用密码 */
const changeAccountStatus = (method, data) => {
  /* 防止多次提交 */
  disabledbtn.value = true;
  formLoading.value = true;
  Request[method](data)
    .then((res) => {
      disabledbtn.value = false;
      formLoading.value = false;
      ElMessage.success(res.msg);
      getTableInfo();
    })
    .catch((res) => {
      disabledbtn.value = false;
      formLoading.value = false;
    });
}

/* 获取表格信息 */
getTableInfo();
getOrganizationInfo();
getRoleInfo();
</script>


<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.warning {
  color: #e6a23c;
}

.cyan {
  color: #67c23a;
}

.mr10 {
  margin-right: 10px;
}

.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 修改该属性值  查询条件，查询结果得样式 */
.el-breadcrumb {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.el-upload--text {
  width: auto;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* 图片上传 start */
.w-spec .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.w-spec :deep(.el-upload--text) {
  width: inherit;
}

.w-spec .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.w-spec .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
}

.w-spec .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.w-spec .avatar-uploader :deep(.el-upload--text) {
  height: inherit;
  padding: 2px 2px;
  color: #409eff;
}

.w-spec .wzg-continer-img {
  position: relative;
  display: inline-block;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;

  .wzg-img {
    width: inherit;
    height: inherit;
  }

  .el-icon-close {
    display: none;
  }
}

/* 图片删除按钮 start*/
.wzg-continer-img:hover .el-icon-close {
  position: absolute;
  top: 1px;
  right: -1px;
  z-index: 1000;
  display: inline-block;
  width: 24px;
  height: 24px;
  padding: 5px;
  cursor: pointer;
  background-color: rgba($color: #f00, $alpha: 0.8);
  color: #fff;
  border-radius: 2px;
  transition: 0.5s;
}

.w-spec .el-icon-close:hover {
  opacity: 0.8;
}
</style>